package com.innovation.ic.cyz.base.service.cyz.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.innovation.ic.cyz.base.mapper.cyz.CategoriesPropertyCyzMapper;
import com.innovation.ic.cyz.base.mapper.cyz.ProductPropertyMapper;
import com.innovation.ic.cyz.base.model.cyz.ProductProperty;
import com.innovation.ic.cyz.base.pojo.enums.RedisKeyPrefixEnum;
import com.innovation.ic.cyz.base.pojo.global.ServiceResult;
import com.innovation.ic.cyz.base.pojo.variable.cyz.device_selection_parameter.DeviceSelectionParamPojo;
import com.innovation.ic.cyz.base.pojo.variable.cyz.device_selection_parameter.DeviceSelectionParameterQueryListRespPojo;
import com.innovation.ic.cyz.base.service.cyz.ProductPropertyService;
import com.innovation.ic.cyz.base.vo.cyz.deviceSelectionParameter.DeviceSelectionParameterFuzzyQueryVo;
import com.innovation.ic.cyz.base.vo.pve_standard.ps_property.PsPropertyVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
//@Transactional
public class ProductPropertyServiceImpl extends ServiceImpl<ProductPropertyMapper, ProductProperty> implements ProductPropertyService {
    private static final Logger log = LoggerFactory.getLogger(ProductPropertyServiceImpl.class);

    @Resource
    private ProductPropertyMapper productPropertyMapper;

    @Resource
    private CategoriesPropertyCyzMapper categoriesPropertyCyzMapper;

    @Autowired
    protected ServiceHelper serviceHelper;

    /**
     * 清空products_property表数据
     */
    @Override
    public void truncateProductProperty() {
        productPropertyMapper.truncateProductProperty();
    }

    /**
     * 批量插入ProductProperty表数据
     *
     * @param list 需要插入的数据
     * @return 返回插入结果
     */
    @Override
    public ServiceResult<Boolean> batchInsertProductPropertyList(List<ProductProperty> list) throws InterruptedException {
        boolean result = Boolean.FALSE;
        String message = ServiceResult.INSERT_FAIL;
        //this.batchInsertProductPropertysRedis(list);
        List<ProductProperty> insertDataList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            insertDataList.add(list.get(i));

            // insertDataList数据够了10000条进行入库处理
            if (insertDataList.size() == 10000) {
                Integer insertCount = productPropertyMapper.insertBatchSomeColumn(insertDataList);
                if (insertCount > 0) {
                    result = Boolean.TRUE;
                    message = ServiceResult.INSERT_SUCCESS;
                    Thread.sleep(200);
                }
                insertDataList = new ArrayList<>();
            } else {
                // 最后一条数据处理完且insertDataList有数据保存到数据库
                if (i == list.size() - 1 && insertDataList.size() > 0) {
                    Integer insertCount = productPropertyMapper.insertBatchSomeColumn(insertDataList);
                    if (insertCount > 0) {
                        result = Boolean.TRUE;
                        message = ServiceResult.INSERT_SUCCESS;
                        Thread.sleep(200);
                    }
                    insertDataList = new ArrayList<>();
                }
            }
        }

        ServiceResult<Boolean> serviceResult = new ServiceResult<>();
        serviceResult.setResult(result);
        serviceResult.setSuccess(result);
        serviceResult.setMessage(message);
        return serviceResult;
    }

    @Override
    public Integer total() {
        return this.baseMapper.selectCount(new QueryWrapper<>());
    }

    @Override
    public List<ProductProperty> findByPage(int pageNum, int pageSize) {
        int start = pageNum * pageSize;
        int end = start + pageSize;
        if (start > 0) {
            start += 1;
        }
        return this.baseMapper.findByPage(start, end);
    }

    /**
     * 查询筛选参数
     *
     * @param psPropertyVo           器件选型属性的vo类
     * @param externallyUniqueIdList 器件选型类型包含参数id集合
     * @return
     */
    @Override
    public ServiceResult<DeviceSelectionParameterQueryListRespPojo> getSelectProperties(PsPropertyVo psPropertyVo, List<String> externallyUniqueIdList) {
        // 查询属性信息
        List<DeviceSelectionParamPojo> psProperties = new ArrayList<>();
        if (externallyUniqueIdList != null && !externallyUniqueIdList.isEmpty()) {
            // 根据器件选型类型包含参数id集合查询分类对应属性表数据集合
            psProperties = categoriesPropertyCyzMapper.getPropertyCyzByIdList(externallyUniqueIdList);
            if (psProperties != null && psProperties.size() > 0) {
                List<String> propertyIds = psProperties.stream().map(DeviceSelectionParamPojo::getPropertyId).collect(Collectors.toList());

                List<ProductProperty> productsPropertyList = baseMapper.findPropertyCyzValuesByPropertyIds(propertyIds);

                psProperties = psProperties.stream().map(item -> {
                    List<ProductProperty> thePropertyValues = productsPropertyList.stream()
                            .filter(t -> t.getPropertyId().equals(item.getPropertyId()))
                            .collect(Collectors.toList());
                    if (thePropertyValues != null && !thePropertyValues.isEmpty()) {
                        List<String> valueText = thePropertyValues.stream().map(t -> t.getText()).collect(Collectors.toList());
                        item.setValueText(valueText);
                    }
                    return item;
                }).collect(Collectors.toList());
            }
        }

        DeviceSelectionParameterQueryListRespPojo result = new DeviceSelectionParameterQueryListRespPojo();
        result.setProperties(psProperties);

        ServiceResult<DeviceSelectionParameterQueryListRespPojo> serviceResult = new ServiceResult<>();
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        serviceResult.setResult(result);
        return serviceResult;
    }

    /**
     * 参数筛选模糊查询
     *
     * @param deviceSelectionParameterFuzzyQueryVo 参数筛选模糊查询的vo类
     * @return
     */
    @Override
    public ServiceResult<List<String>> queryFuzzyParamSelectPropertiesCyz(DeviceSelectionParameterFuzzyQueryVo deviceSelectionParameterFuzzyQueryVo) {
        ServiceResult<List<String>> serviceResult = new ServiceResult<>();
        serviceResult.setResult(baseMapper.queryFuzzyParamSelectPropertiesCyz(deviceSelectionParameterFuzzyQueryVo));
        serviceResult.setMessage(ServiceResult.SELECT_SUCCESS);
        serviceResult.setSuccess(Boolean.TRUE);
        return serviceResult;
    }

    /***
     * 批量保存redis
     * @param list
     */
    private void batchInsertProductPropertysRedis(List<ProductProperty> list) {
        String key = RedisKeyPrefixEnum.TABLE.getCode() + ":" + RedisKeyPrefixEnum.TABLE_PRODUCT_PROPERTY.getCode();
        try {
            List<ProductProperty> insertDataList = new ArrayList<>();
            for (int i = 0; i < list.size(); i++) {
                insertDataList.add(list.get(i));
                if (i % 8000 == 0 && i != 0) {
                    serviceHelper.getRedisManager().lPushAll(key, insertDataList);
                    this.sleep();
                    insertDataList.clear();
                }
            }
            if (!CollectionUtils.isEmpty(insertDataList)) {
                serviceHelper.getRedisManager().lPushAll(key, insertDataList);
            }
        } catch (Exception e) {
            log.error("定时任务,保存Redis key :  {} 失败 ", key, e);
        }

    }


    /**
     * 线程处理睡眠
     */
    private void sleep() {
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            log.error("线程睡眠发生异常", e);
        }
    }


}